package cron

import (
	"bigdevops/src/common"
	"bigdevops/src/models"
	"context"
	"github.com/prometheus/alertmanager/template"
	"go.uber.org/zap"
	"strconv"
)

func (ac *AlertCache) AlertReceiveConsumerManager(ctx context.Context) error {

	for {
		select {
		case <-ctx.Done():
			ac.Sc.Logger.Info("AlertReceiveConsumerManager 收到其他任务退出信号 退出")
			return nil
		case alert := <-ac.AlertReceiveQ:
			go ac.DealWithOneAlertReceive(alert)
		}

	}

}

// 👨‍💻
// 1. 拿到sendGroup
// 2. 根据sendGroup中的 通道，去生成告警信息
// 3. 根据sendGroup 发送人，值班组 发送
// 4. 告警升级判断：替换发送人，替换内容为已升级
// 5. 存到数据库中 告警事件表
func (ac *AlertCache) DealWithOneAlertReceive(alert template.Alert) {

	// 获取send_group_id
	sendGroupId, exists := alert.Labels[common.MONITOR_ALERT_MATCH_KEY]
	if !exists {
		ac.Sc.Logger.Info("alert消费者收到告警信息，sendGroupId不存在",
			zap.Any("告警", alert),
		)
		return
	}

	ruleId, exists := alert.Labels[common.MONITOR_ALERT_RULE_KEY]
	if !exists {
		ac.Sc.Logger.Info("alert消费者收到告警信息，ruleId不存在",
			zap.Any("告警", alert),
		)
		return
	}

	ruleIdInt, _ := strconv.Atoi(ruleId)
	sendGroupIdInt, _ := strconv.Atoi(sendGroupId)

	// 从缓存中获取sendGroup
	sendGroup := ac.GetSendGroupById(sendGroupId)
	if sendGroup == nil {
		ac.Sc.Logger.Info("alert消费者收到告警信息，跟sendGroupId去缓存中查询结果不存在",
			zap.Any("sendGroupId", sendGroupId),
			zap.Any("告警", alert),
		)
		return
	}

	// 从缓存中获取User
	createUser := ac.GetUserById(sendGroup.UserID)

	// 从缓存中获取rulle
	rule := ac.GetRuleById(ruleId)

	ac.Sc.Logger.Info("alert消费者收到告警信息",
		zap.Any("告警", alert),
		zap.Any("开始时间", alert.StartsAt),
		zap.Any("结束时间", alert.EndsAt),
		//zap.Any("发送组", sendGroup),
		//zap.Any("createUser", createUser),
		//zap.Any("规则", rule),
	)
	// 判断是否已升级
	upgradeNeed := false
	if alert.Status == common.MONITOR_ALERT_STATUS_FIRING && sendGroup.FirstUpgradeUsers != nil && len(sendGroup.FirstUpgradeUsers) > 0 {
		upgradeNeed = true
	}

	status := alert.Status
	if upgradeNeed {
		status = common.MONITOR_ALERT_STATUS_UPGRADED
	}

	// 构造event
	event := &models.MonitorAlertEvent{
		AlertName:   alert.Labels[common.MONITOR_ALERT_NAME_KEY],
		Fingerprint: alert.Fingerprint,
		Status:      status,
		RuleId:      uint(ruleIdInt),
		Labels:      common.GenStringArrayByMap(alert.Labels),
		SendGroupId: uint(sendGroupIdInt),
	}

	// 处理event
	err := event.UpdateOrCreateOne()
	if err != nil {
		ac.Sc.Logger.Debug("报错alert到event出错",
			zap.Error(err),
			zap.Any("告警", alert),
			zap.Any("发送组", sendGroup),
			zap.Any("createUser", createUser),
			zap.Any("规则", rule),
		)
	}

	event, err = models.GetMonitorAlertEventByFingerprintId(alert.Fingerprint)
	if err != nil {
		ac.Sc.Logger.Error("查询event出错",
			zap.Error(err),
			zap.Any("告警", alert),
			zap.Any("发送组", sendGroup),
			zap.Any("createUser", createUser),
			zap.Any("规则", rule),
		)
	}
	event.FillFrontAllData()
	// 处理告警信息
	ac.GenerateFeishuCardContentOneAlert(alert, event, rule, sendGroup)
}
